import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import Footer from "@/components/Footer/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import { ScrollView, View } from "@tarojs/components";
import {
  Button,
  Tabs,
  Pagination,
  Toast,
  Dialog,
  Popup,
  Form,
  Cell,
  Radio,
  Textarea,
  Empty,
  Image,
} from "@taroify/core";
import { useEffect, useRef, useState } from "react";
import { PhotoFail } from "@taroify/icons";
import { requestPOST } from "@/request";

export default function Index() {
  const [current1, setCurrent1] = useState(1);
  const [count1, setCount1] = useState(0);
  const [person1, setPerson1] = useState<any>([]);
  const [current2, setCurrent2] = useState(1);
  const [count2, setCount2] = useState(0);
  const [person2, setPerson2] = useState<any>([]);
  const [active, setActive] = useState(0);
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({
    id: null,
    remark: "",
    status: 2,
  });
  const tabName = useRef("1"); // 公用一个审核弹窗，区分作用

  const getPerson1 = (page?: number) => {
    requestPOST("promotion/business/businessLookPromotionUser", {
      pageTotal: 1,
      pageNum: page || current1,
      pageSize: 6,
      status: 0,
    }).then((res: any) => {
      setCount1(Math.ceil(res.total / 6));
      setPerson1([...res.promotionUserLists]);
    });
  };
  const getPerson2 = (page?: number) => {
    requestPOST("promotion/business/businessLookPromotionApply", {
      pageNum: page || current2,
      pageSize: 6,
      status: 0,
      userId: 0,
    }).then((res: any) => {
      setCount2(Math.ceil(res.total / 6));
      setPerson2([...res.applyPromotionLists]);
    });
  };
  const handleChange1 = (page: number) => {
    setCurrent1(page);
    getPerson1(page);
  };
  const handleChange2 = (page: number) => {
    setCurrent2(page);
    getPerson2(page);
  };
  const jiebang = (item) => {
    Dialog.confirm({
      title: "提示",
      message: "您确定要解绑吗？",
      onConfirm() {
        requestPOST(
          `promotion/business/unBindPromotionUser/${item.userId}`
        ).then(() => {
          Toast.open({ type: "success", message: "解绑成功" });
          getPerson1();
        });
      },
    });
  };
  const onSubmit = () => {
    requestPOST(
      tabName.current == "1"
        ? "promotion/business/businessAuditApply"
        : "promotion/business/businessAuditCash",
      {
        ...form,
      }
    ).then(() => {
      Toast.open({ type: "success", message: "审核成功" });
      setOpen(false);
      if (tabName.current == "1") {
        getPerson2();
      } else {
        getRecord1();
      }
      formRef.current?.reset();
    });
  };

  const [record, setRecord] = useState<any>([]);
  const [current3, setCurrent3] = useState(1);
  const [count3, setCount3] = useState(0);

  const getRecord = (page?: number) => {
    requestPOST("promotion/business/businessLookCommissionList", {
      pageNum: page || current3,
      pageSize: 6,
      commodityId: 0,
      userId: 0,
    }).then((res: any) => {
      setCount3(Math.ceil(res.total / 6));
      setRecord([...res.promotionCommissionLists]);
    });
  };

  const handleChange3 = (page) => {
    setCurrent3(page);
    getRecord(page);
  };

  const [record1, setRecord1] = useState<any>([]);
  const [current4, setCurrent4] = useState(1);
  const [count4, setCount4] = useState(0);

  const getRecord1 = (page?: number) => {
    requestPOST("promotion/business/businessPromotionCashList", {
      pageNum: page || current4,
      pageSize: 6,
      status: 0,
      userId: 0,
    }).then((res: any) => {
      setCount4(Math.ceil(res.total / 6));
      setRecord1([...res.promotionCashListList]);
    });
  };

  const handleChange4 = (page) => {
    setCurrent4(page);
    getRecord(page);
  };

  useEffect(() => {
    getPerson1();
    getPerson2();
    getRecord();
    getRecord1();
  }, []);

  const formRef = useRef<any>();

  return (
    <View className="taroBox">
      <HeaderSearch />
      <Header />
      <View>
        <GoodsTitle title="推广人员" isMore={false} />
        <Tabs>
          <Tabs.TabPane title="推广人员">
            <View style={{ padding: "14px" }}>
              <View
                style={{ display: "flex", alignItems: "center", gap: "10px" }}
              >
                <Button
                  size="small"
                  variant={active == 0 ? "contained" : "outlined"}
                  color="primary"
                  onClick={() => setActive(0)}
                >
                  查看已绑定的推广人员
                </Button>
                <Button
                  size="small"
                  variant={active == 1 ? "contained" : "outlined"}
                  color="primary"
                  onClick={() => setActive(1)}
                >
                  查看绑定推广申请
                </Button>
              </View>
              {active === 0 && (
                <View>
                  <View
                    style={{
                      marginTop: "10px",
                      display: "flex",
                      flexDirection: "column",
                      gap: "20px",
                    }}
                  >
                    {!person1.length && (
                      <Empty>
                        <Empty.Image />
                        <Empty.Description>暂无数据</Empty.Description>
                      </Empty>
                    )}
                    {person1.map((item) => (
                      <View
                        key={item.userId}
                        style={{
                          display: "flex",
                          flexDirection: "column",
                          gap: "5px",
                          boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                          padding: "10px",
                          fontSize: "14px",
                        }}
                      >
                        <View style={{ fontSize: "16px" }}>
                          昵称：{item.userName}
                        </View>
                        <View>电话：{item.phone}</View>
                        <View>邮箱：{item.email}</View>
                        <View>推广厂家：{item.promotionBalance}</View>
                        <View>
                          <Button
                            color="danger"
                            size="small"
                            variant="outlined"
                            onClick={() => jiebang(item)}
                          >
                            解绑
                          </Button>
                        </View>
                      </View>
                    ))}
                  </View>
                  <View
                    style={{ marginBlock: "1.25rem", padding: "0 .875rem" }}
                  >
                    <Pagination
                      current={current1}
                      siblingCount={1}
                      count={count1}
                      onChange={(page) => handleChange1(page)}
                    >
                      <Pagination.Item type="start-ellipsis" />
                      <Pagination.Item type="end-ellipsis" />
                    </Pagination>
                  </View>
                </View>
              )}
              {active === 1 && (
                <View>
                  <View
                    style={{
                      marginTop: "10px",
                      display: "flex",
                      flexDirection: "column",
                      gap: "20px",
                    }}
                  >
                    {!person2.length && (
                      <Empty>
                        <Empty.Image />
                        <Empty.Description>暂无数据</Empty.Description>
                      </Empty>
                    )}
                    {person2.map((item) => (
                      <View
                        key={item.userId}
                        style={{
                          display: "flex",
                          flexDirection: "column",
                          gap: "5px",
                          boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                          padding: "10px",
                          fontSize: "14px",
                        }}
                      >
                        <View style={{ fontSize: "16px" }}>
                          昵称：{item.userName}
                        </View>
                        <View>电话：{item.phone}</View>
                        <View>邮箱：{item.email}</View>
                        <View>审核回复：{item.remark}</View>
                        <View>
                          状态：{item.status === 1 ? "审核中" : "已通过"}
                        </View>
                        <View>申请时间：{item.createTime}</View>
                        <View>
                          <Button
                            color="primary"
                            size="small"
                            variant="outlined"
                            disabled={item.status !== 1}
                            onClick={() => {
                              setOpen(true);
                              tabName.current = "1";
                              setForm({ ...form, id: item.id });
                            }}
                          >
                            审核
                          </Button>
                        </View>
                      </View>
                    ))}
                  </View>
                  <View
                    style={{ marginBlock: "1.25rem", padding: "0 .875rem" }}
                  >
                    <Pagination
                      current={current2}
                      siblingCount={1}
                      count={count2}
                      onChange={(page) => handleChange2(page)}
                    >
                      <Pagination.Item type="start-ellipsis" />
                      <Pagination.Item type="end-ellipsis" />
                    </Pagination>
                  </View>
                </View>
              )}
            </View>
          </Tabs.TabPane>
          <Tabs.TabPane title="推广记录">
            <View style={{ padding: "14px" }}>
              <View
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "10px",
                }}
              >
                {!record.length && (
                  <Empty>
                    <Empty.Image />
                    <Empty.Description>暂无数据</Empty.Description>
                  </Empty>
                )}
                {record.map((item, index) => (
                  <View
                    key={index}
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      gap: "5px",
                      boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                      padding: "10px",
                      fontSize: "14px",
                    }}
                  >
                    <Image
                      src={
                        item.image
                          ? process.env.TARO_APP_API + item.image
                          : "error"
                      }
                      width={40}
                      height={40}
                      mode="aspectFill"
                      fallback={<PhotoFail />}
                    />
                    <View>提成推广用户名称:{item.promotionUserName}</View>
                    <View>下单商品名称：{item.commodityName}</View>
                    <View>商品支付价格：{item.payPrice}</View>
                    <View>提成比例：{item.commissionProportion}</View>
                    <View>提成价格：{item.commissionPrice}</View>
                    <View>提成时间：{item.createTime}</View>
                  </View>
                ))}
              </View>
              <View style={{ marginBlock: "1.25rem", padding: "0 .875rem" }}>
                <Pagination
                  current={current3}
                  siblingCount={1}
                  count={count3}
                  onChange={(page) => handleChange3(page)}
                >
                  <Pagination.Item type="start-ellipsis" />
                  <Pagination.Item type="end-ellipsis" />
                </Pagination>
              </View>
            </View>
          </Tabs.TabPane>
          <Tabs.TabPane title="提现申请">
            <View style={{ padding: "14px" }}>
              <View
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "10px",
                }}
              >
                {!record1.length && (
                  <Empty>
                    <Empty.Image />
                    <Empty.Description>暂无数据</Empty.Description>
                  </Empty>
                )}
                {record1.map((item) => (
                  <View
                    key={item.userId}
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      gap: "5px",
                      boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                      padding: "10px",
                      fontSize: "14px",
                    }}
                  >
                    <View>受益人姓名:{item.beneficiaryName}</View>
                    <View>受益人地址:{item.beneficiaryAddress}</View>
                    <View>受益人账号：{item.beneficiaryAccNo}</View>
                    <View>银行地址：{item.addressOfBank}</View>
                    <View>SWIFT码：{item.swiftCode}</View>
                    <View>银行代码：{item.postCode}</View>
                    <View>分行代码：{item.branchCode}</View>
                    <View>受益人银行：{item.beneficiaryBank}</View>
                    <View>国家/地区：{item.address}</View>
                    <View>提现金额：{item.promotionBalance}</View>
                    <View>申请提现时间：{item.createTime}</View>
                    <View>审核回复：{item.remark}</View>
                    <View>
                      审核状态：
                      {item.status == 1
                        ? "审核中"
                        : item.status == 2
                        ? "已拒绝"
                        : "已通过"}
                    </View>
                    {item.status === 1 && (
                      <View style={{ marginTop: "10px" }}>
                        <Button
                          color="primary"
                          variant="outlined"
                          size="small"
                          onClick={() => {
                            setOpen(true);
                            tabName.current = "2";
                            setForm({ ...form, id: item.id });
                          }}
                        >
                          审核
                        </Button>
                      </View>
                    )}
                  </View>
                ))}
              </View>
              <View style={{ marginBlock: "1.25rem", padding: "0 .875rem" }}>
                <Pagination
                  current={current4}
                  siblingCount={1}
                  count={count4}
                  onChange={(page) => handleChange4(page)}
                >
                  <Pagination.Item type="start-ellipsis" />
                  <Pagination.Item type="end-ellipsis" />
                </Pagination>
              </View>
            </View>
          </Tabs.TabPane>
        </Tabs>
      </View>
      <Footer />

      <Popup open={open} placement="center" style={{ height: "auto" }} rounded lock={false}>
        <View style={{ width: "90vw", padding: "14px 0" }}>
          <Form ref={formRef} defaultValues={form} onSubmit={onSubmit}>
            <Cell.Group inset>
              <Form.Item
                name="status"
                rules={[{ required: true, message: "请选择审核状态" }]}
              >
                <Form.Label>审核状态</Form.Label>
                <Form.Control>
                  <Radio.Group
                    value={form.status}
                    onChange={(value) => setForm({ ...form, status: value })}
                  >
                    <Radio name={2}>已拒绝</Radio>
                    <Radio name={3}>已通过</Radio>
                  </Radio.Group>
                </Form.Control>
              </Form.Item>
              <Form.Item
                name="remark"
                rules={[{ required: true, message: "请填写审核备注" }]}
              >
                <Form.Label>审核备注</Form.Label>
                <Form.Control>
                  <Textarea
                    value={form.remark}
                    onChange={(e) =>
                      setForm({ ...form, remark: e.detail.value })
                    }
                    style={{ height: "5rem" }}
                    limit={255}
                  ></Textarea>
                </Form.Control>
              </Form.Item>
            </Cell.Group>
            <View
              style={{
                margin: "1rem",
                display: "flex",
                alignItems: "center",
                gap: "30px",
              }}
            >
              <Button
                shape="round"
                block
                color="primary"
                variant="outlined"
                onClick={() => {
                  setOpen(false);
                  setForm({
                    id: null,
                    remark: "",
                    status: 2,
                  });
                }}
              >
                取消
              </Button>
              <Button shape="round" block color="primary" formType="submit">
                提交
              </Button>
            </View>
          </Form>
        </View>
      </Popup>
    </View>
  );
}
